<?php

namespace app\commission;

use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\util\Debug;

class ReceivedCommission
{
    public static function done($order_id)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $commissions = UserCommission::find()
                ->where(['order_id' => $order_id])
                // status => 0, 10
                // ->andWhere(['!=', 'status', 1])
                ->andWhere(['status' => 0])
                ->all();
            foreach ($commissions as $c) {
                $c->status = 1;
                $c->save();

                $account = UserAccount::findOne(['user_id' => $c->user_id]);
                if ($account) {
                    if ($account->await_balance >= $c->balance) {
                        $account->await_balance -= $c->balance;
                        $account->done_balance += $c->balance;
                        $account->balance += $c->balance;
                        $account->save();
                    }
                }
            }
            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            Debug::commission('commission', $e->getMessage());
        }
    }
}